package mx.itesm.twritter.server.map;

import java.util.ArrayList;
import java.util.List;

import mx.itesm.twritter.shared.map.Node;


public class AStar {
	
	private final String ROUTE_PATH = "../src/mx/itesm/twritter/server/PyOSMRoute/";
	private final String NIX_MAP = "../src/mx/itesm/twritter/server/PyOSMRoute/map.osm";

	
	private final String TRANSPORTATION = "car";
	private final PyCalls py;
	
	public AStar() {
		py = new PyCalls(ROUTE_PATH, NIX_MAP);
	}
	
	public AStar(String lib, String path) {
		py = new PyCalls(lib, path);
	}
	
	/**
	 * Find the A* route from start to end
	 * @param start Start node's id
	 * @param end End node's id
	 * @return A list of nodes that represent the route from start to end
	 */
	public List<Node> route(int start, int end) {
		py.CalculateRoute(start, end, TRANSPORTATION);
		
		return String2Route(py.GetRoute());
	}
	
	/**
	 * Alternative call to route
	 * @param start Start node
	 * @param end End node
	 * @return A list of nodes that represent the route from start to end
	 */
	public List<Node> route(Node start, Node end) {
		return route(start.getId(), end.getId());
	}
	
	private List<Node> String2Route(String out) {
		
		//System.out.println("<<Route>> " + out);
		if(out.isEmpty()) {
			return new ArrayList<Node>();
		}
		
		// string like "[(19.4253363, -99.1767879), (19.4254708, -99.1768561), (19.4272787, -99.1775843)..." etc
		
		List<Node> r = new ArrayList<Node>();
		
		// remove the "Route: " beginning
		String removed = out.replace("[", "").replace("]", "").replace("(", "").replace(")","");
		String[] nodes = removed.split(",");
		
		for(int i=0; i<nodes.length; i=i+2) {
			if (nodes[i].trim().startsWith("(gave_up)") || nodes[i].trim().startsWith("(no_route)")) {
				return new ArrayList<Node>();
			}
			Double longitude = Double.parseDouble(nodes[i]);
			Double latitude  = Double.parseDouble(nodes[i+1]);
			
			r.add(new Node(longitude, latitude));
		}
		//System.out.println(r);
		return r;
	}
	
	
}
